//
//  HomePageController.m
//  qiuShiJiangHu
//
//  Created by xalo on 16/1/25.
//  Copyright © 2016年 糗事江湖项目组. All rights reserved.
//

#import "HomePageController.h"
#import "SegmentControlView.h"
#import "ArticleCell.h"
#import "VideoCell.h"
#import "PictureCell.h"
#import "HttpHelper.h"
#import "HttpHelperWithVideo.h"
#import "HttpHelperWithPicture.h"
#import "ArticleDetailViewController.h"
#import "VideoDetailViewController.h"
#import "PictureDetailViewController.h"
#import "HomePageModel.h"
#import "VideoModel.h"
#import "ImageModel.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

@interface HomePageController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) SegmentControlView *segmentView;
@property (strong, nonatomic) IBOutlet UIScrollView *homeScrollView;
@property (strong, nonatomic) IBOutlet UITableView *articleTableview;
@property (strong, nonatomic) IBOutlet UITableView *videoTableView;
@property (strong, nonatomic) IBOutlet UITableView *pictureTableView;
@property (strong, nonatomic) IBOutlet UIView *essenceView;
@property (nonatomic,strong) ArticleCell *articleCell;
@property (nonatomic,strong) VideoCell *videoCell;
@property (nonatomic,strong) PictureCell *pictureCell;
@property (nonatomic,strong) AVPlayerViewController *moviePlayer;
@property(nonatomic,strong)NSNotificationCenter *notificationCenter;
@property (nonatomic,strong) UIWebView *webView;
@end

@implementation HomePageController

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}


//添加分段控制器
-(void)addSegmentForHomeController
{
    self.segmentView=[[SegmentControlView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    
    [self.view addSubview:self.segmentView];

}

//当scrollView滑动时和segment对应
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
 //计算当前的偏移量
    CGFloat offSet=scrollView.contentOffset.x;
    
    CGFloat width=scrollView.frame.size.width;
    
    NSInteger number=(NSInteger)offSet/width;
    
    if (number >= 1) {
         self.segmentView.segment.selectedSegmentIndex=number;
    }
    [self setData];
}

//当segment的index改变时和scrollView对应
-(void)changeSegmentIndex
{
  //获取当前segement的index
    NSInteger number=self.segmentView.segment.selectedSegmentIndex;
    //计算偏移量
    CGFloat offSet=self.homeScrollView.frame.size.width*number;
    [self.homeScrollView setContentOffset:CGPointMake(offSet, 0) animated:YES];
    [self setData];
}
//请求数据方法
-(void)setData
{
    if (self.segmentView.segment.selectedSegmentIndex==0) {

        [[HttpHelper sharedManager] fectchSourceWithUrl:kHomepageUrl(30, 1) block:^{
            [self.articleTableview reloadData];
        }];
    }else if(self.segmentView.segment.selectedSegmentIndex==1){
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [[HttpHelperWithVideo sharedManager] fectchSourceWithUrl:kVideoUrl(30, 3) block:^{
        [self.videoTableView reloadData];
        [MBProgressHUD hideHUDForView:self.view  animated:YES];
    }];        
        
    }else if (self.segmentView.segment.selectedSegmentIndex==2){
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HttpHelperWithPicture sharedManager] fectchSourceWithUrl:kImages block:^{
            [self.pictureTableView reloadData];
            [MBProgressHUD hideHUDForView:self.view  animated:YES];
        }];
    }else{
       self.webView=[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.qiushibaike.com/pic/"]];
        [self.webView loadRequest:request];
        [self.essenceView addSubview:self.webView];
    }
}

//设置代理
-(void)setDelegate
{
    self.homeScrollView.delegate=self;
    self.articleTableview.dataSource=self;
    self.articleTableview.delegate=self;
    self.videoTableView.dataSource=self;
    self.videoTableView.delegate=self;
    self.pictureTableView.dataSource=self;
    self.pictureTableView.delegate=self;
    
}
//用xib创建单元格首先注册单元格
-(void)registTableViewCell
{
    [self.articleTableview registerNib:[UINib nibWithNibName:@"ArticleCell" bundle:nil] forCellReuseIdentifier:@"articleCell"];
    [self.videoTableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:@"videoCell"];
    [self.pictureTableView registerNib:[UINib nibWithNibName:@"PictureCell" bundle:nil] forCellReuseIdentifier:@"picCell"];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setDelegate];
    
    [self refreshData];
    
    //设置导航栏背景图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"640x130"] forBarMetrics:(UIBarMetricsDefault)];
    self.navigationController.navigationBar.translucent = NO;
    
    //添加进度指示器
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [[HttpHelper sharedManager] fectchSourceWithUrl:kHomepageUrl(30, 2) block:^{
    
        [self.articleTableview reloadData];
        
        [MBProgressHUD hideHUDForView:self.view  animated:YES];
    }];
    
    [self addSegmentForHomeController];
    
    [self.segmentView.segment addTarget:self action:@selector(changeSegmentIndex) forControlEvents:UIControlEventValueChanged];
    
    [self registTableViewCell];
}

//上拉刷新,下拉加载
-(void)refreshData
{
    //下拉刷新
    self.articleTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.articleTableview reloadData];
            
            [self.articleTableview.mj_header endRefreshing];
        });
    }];
    //上拉加载
    self.articleTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self loadMoreDate];
            
            [self.articleTableview reloadData];
            
            [self.articleTableview.mj_footer endRefreshing];
        });
    }];
}

//加载数据
-(void)loadMoreDate
{
    [[HttpHelper sharedManager] fectchSourceWithUrl:kHomepageUrl(30, 1) block:^{
        [self.articleTableview reloadData];
    }];
}
//进入到详情页面
-(void)enterToDetailVC
{
    ArticleDetailViewController *articleDVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ArticleDVC"];    

    NSInteger number=self.articleCell.commentButton.tag-1;
    articleDVC.index=number;
    
    HomePageModel *model = [[HttpHelper sharedManager] returnModelWithIndex:articleDVC.index ];
    
    NSLog(@"%@",articleDVC.homeModel);

    articleDVC.ID = model.ID;
    
    [self.navigationController pushViewController:articleDVC animated:YES];
}
-(void)enterToVideoDetailVC
{
    VideoDetailViewController *videoDVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"VideoDVC"];
    
    NSInteger number=self.videoCell.commentButton.tag-1;
    videoDVC.index=number;
    
    VideoModel *model = [[HttpHelperWithVideo sharedManager] returnModelWithIndex:videoDVC.index ];
    
    videoDVC.ID = model.ID;
    
    [self.navigationController pushViewController:videoDVC animated:YES];

}
-(void)enterToPictureDetailVC
{
    PictureDetailViewController *picDVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PictureDVC"];
    
    NSInteger number=self.pictureCell.commentButton.tag-1;
    picDVC.index=number;
    
    ImageModel *model = [[HttpHelperWithPicture sharedManager] returnModelWithIndex:picDVC.index ];
    
    picDVC.ID = model.ID;
    
    [self.navigationController pushViewController:picDVC animated:YES];
}

#pragma mark--dataSource必须实现的方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.articleTableview) {
        return [[HttpHelper sharedManager] countOfModelArray];
    }else if (tableView == self.videoTableView)
    {
        return  [[HttpHelperWithVideo sharedManager] countOfModelArray];
    
    }else
    {
        return [[HttpHelperWithPicture sharedManager] countOfModelArray];
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.articleTableview) {

    self.articleCell=[tableView dequeueReusableCellWithIdentifier:@"articleCell" forIndexPath:indexPath];
       HomePageModel  *model=[[HttpHelper sharedManager] returnModelWithIndex:indexPath.row];        
        [self.articleCell setContentViewWithModel:model];

        //给评论按钮添加点击事件
        [self.articleCell.commentButton addTarget:self action:@selector(enterToDetailVC) forControlEvents:(UIControlEventTouchUpInside)];
        self.articleCell.commentButton.tag=indexPath.row;

        return self.articleCell;
    }else if (tableView==self.videoTableView){
        self.videoCell=[tableView dequeueReusableCellWithIdentifier:@"videoCell" forIndexPath:indexPath];
       VideoModel *model=[[HttpHelperWithVideo sharedManager] returnModelWithIndex:indexPath.row];
        
        [self.videoCell setContentViewWithModel:model];
        
        self.videoCell.playButton.tag = indexPath.row;
        
        [self.videoCell.playButton addTarget:self action:@selector(playVideo) forControlEvents:(UIControlEventTouchUpInside)];
        //给评论按钮添加点击事件
        [self.videoCell.commentButton addTarget:self action:@selector(enterToVideoDetailVC) forControlEvents:(UIControlEventTouchUpInside)];
        [self.moviePlayer removeFromParentViewController];
        self.videoCell.commentButton.tag=indexPath.row;
        
        return self.videoCell;
    }else {
        self.pictureCell=[tableView dequeueReusableCellWithIdentifier:@"picCell" forIndexPath:indexPath];
        ImageModel *model = [[HttpHelperWithPicture sharedManager] returnModelWithIndex:indexPath.row];
        
        [self.pictureCell setContentViewWithModel:model];
        //给评论按钮添加点击事件
        [self.pictureCell.commentButton addTarget:self action:@selector(enterToPictureDetailVC) forControlEvents:(UIControlEventTouchUpInside)];
        self.pictureCell.commentButton.tag=indexPath.row;
        
        return self.pictureCell;
    }
}
//视频播放
-(void)playVideo
{
    NSInteger index = self.videoCell.playButton.tag;
    
    NSLog(@"%ld",index);
    
    VideoModel *model = [[HttpHelperWithVideo sharedManager] returnModelWithIndex:index - 1];
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:model.high_url]];
    
    self.moviePlayer = [[AVPlayerViewController alloc] init];
    
    self.moviePlayer.player = [AVPlayer playerWithPlayerItem:item];
    
    self.moviePlayer.view.frame = CGRectMake(10, 80 + 520 * (index - 1), 355, 355);
    
    [self.videoTableView addSubview:_moviePlayer.view];
    
    [self.moviePlayer.player play];
    
}

//设置单元格高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.articleTableview) {
        
     CGRect bound = [self.articleCell.contentLabel.text boundingRectWithSize:CGSizeMake(self.articleCell.frame.size.width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17.0] forKey:NSFontAttributeName] context:nil];        
        
        return 145 + bound.size.height;
        
    }else if(tableView==self.videoTableView){
        
        return 520;
        
    }else {
        
          CGRect bound = [self.pictureCell.contentLabel.text boundingRectWithSize:CGSizeMake(self.articleCell.frame.size.width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17.0] forKey:NSFontAttributeName] context:nil];
            return 515 + bound.size.height;
        }
   }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.articleTableview) {
        
        HomePageModel *model = [[HttpHelper sharedManager] returnModelWithIndex:indexPath.row];
        
        ArticleDetailViewController *articleDVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ArticleDVC"];
        articleDVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:@"< 糗事  %ld",(long)model.ID] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
        
        articleDVC.index = indexPath.row;
        articleDVC.ID=model.ID;        
        articleDVC.homeModel = model;
        
        [self.navigationController pushViewController:articleDVC animated:YES];
        
    }else if (tableView==self.videoTableView){
        
        VideoModel *model = [[HttpHelperWithVideo sharedManager] returnModelWithIndex:indexPath.row];
        
        VideoDetailViewController *videoDVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"VideoDVC"];
        
        videoDVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:@"< 糗事  %ld",model.ID] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
        
        videoDVC.index = indexPath.row;
        videoDVC.ID=model.ID;
        
        [self.navigationController pushViewController:videoDVC animated:YES];
        
    }else if (tableView==self.pictureTableView){
        
        ImageModel *model = [[HttpHelperWithPicture sharedManager] returnModelWithIndex:indexPath.row];
        
        PictureDetailViewController *pictureDVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PictureDVC"];
        
        pictureDVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:@"< 糗事  %ld",model.ID] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
        
        pictureDVC.index = indexPath.row;
        pictureDVC.ID=model.ID;
        [self.navigationController pushViewController:pictureDVC animated:YES];        
    }
}

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
        [self.moviePlayer.view removeFromSuperview];
        self.moviePlayer=nil;    
}

#pragma mark ---
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
